package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CreateProjectException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.constants.UserConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.EmptyUtil;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.sun.jersey.json.impl.provider.entity.JSONArrayProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    String prefix;

    @Value("${file.oss.endpoint}")
    String endpoint;

    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 上传图片
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if( multipartFile.getSize()==0){
            CreateProjectException.exec(AppHttpCodeEnum.PARAM_INVALID);
        }
        String fileId = null;

        try {
            String filename = UUID.randomUUID().toString().replace("-", "");
            String originalFilename = multipartFile.getOriginalFilename();
            String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileId= fileStorageService.store(prefix,filename+postfix,multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl uploadPicture error: {}",e);
            CreateProjectException.exec(AppHttpCodeEnum.FILE_PUT_ERROR_ADMIND);
        }

        WmUser user = WmThreadLocalUtils.getUser();

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        if(user==null){
            CreateProjectException.exec(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmMaterial.setUserId(user.getId());
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setUrl(fileId);
        save(wmMaterial);

        wmMaterial.setUrl( webSite+fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.校验参数
        if(EmptyUtil.isNullOrEmpty(dto)){
            CreateProjectException.exec(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();
        //2，执行查询
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmMaterial> pageResult = null;
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId());
        //2.1 判断是查询收藏
        if(UserConstants.AP_USER_FLAG_WE_MEDIA.equals(dto.getIsCollection())){
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        pageResult = page(page,wrapper);

        List<WmMaterial> list = pageResult.getRecords();
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        for (WmMaterial wmMaterial : list) {
            wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        }
        pageResponseResult.setData(list);
        return pageResponseResult;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 删除图片
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        if(id== null){
            CreateProjectException.exec(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = getById(id);
        if(EmptyUtil.isNullOrEmpty(wmMaterial)){
            CreateProjectException.exec(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if(count > 0){
            CreateProjectException.exec(AppHttpCodeEnum.PICTURE_IS_USE);
        }


        fileStorageService.delete(wmMaterial.getUrl());
        boolean flag = removeById(id);
        if(!flag){
            CreateProjectException.exec(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消收藏
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.判断参数是否可用
        if(id== null){
            CreateProjectException.exec(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.执行业务 更新状态
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,uid));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}


















